package io.xxx.omni.osc.sdk

import com.alibaba.fastjson.JSONObject
import io.xxx.omni.osc.common.sign
import io.xxx.omni.osc.common.zoneOffset
import io.xxx.omni.osc.domain.Store
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import java.time.LocalDateTime
import java.util.*

@Component
class BbClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "http://api.open.beibei.com/outer_api/out_gateway/route.html"

    fun execute(store: Store, method: String, request: Map<String, Any>): JSONObject {
        val signMap = TreeMap(request)
        signMap["method"] = method
        signMap["timestamp"] = LocalDateTime.now().toEpochSecond(zoneOffset).toString()
        signMap["app_id"] = store.authorization["app_id"]
        signMap["session"] = store.authorization["session"]
        signMap["sign"] = sign(store.authorization["appSecret"], signMap)
        return restTemplate.postForEntity(httpUrl, signMap, JSONObject::class.java).body!!
    }
}